//
//  HNurseAssessDetailEditViewController.m
//  NursingManages
//
//  Created by Zhen Huang on 17/7/12.
//  Copyright © 2017年 huangzhen. All rights reserved.
//

#import "HNurseAssessDetailEditViewController.h"
#import <TMCache.h>
#import "HQCDepartViewController.h"
#import "Model_Hr_Ns_Inspect_New.h"
#import "Model_Pub_Employee.h"
#import "Model_Hr_InspectDetail_New.h"
#import "HQualitySave.h"
#import "InitDbTableQuality.h"
@interface HNurseAssessDetailEditViewController ()



@property (nonatomic,strong)UITableView *theTableView;

@property (nonatomic,strong) HQc_codeModel *theParamCodeModel;

@property (nonatomic,strong)NSArray *theSecondCodeArray;
@property (nonatomic,strong)NSMutableDictionary *theDataSource;
@property (nonatomic,assign)NSInteger typeTag;


// 界面数据保存到此
// 主表
@property(nonatomic,strong) Model_Hr_Ns_Inspect_New *theInspectModel;
// 明细表
@property(nonatomic,strong) NSMutableArray *theInspectDetailArray;



@end

@implementation HNurseAssessDetailEditViewController


-(instancetype)initWithRootCode:(HQc_codeModel*) codeModel
                        typeTag:(NSInteger)typeTag
                   InspectModel:(Model_Hr_Ns_Inspect_New *)InspectModel
{
    self.typeTag = typeTag;
    self.InspectModel = InspectModel;
    // 主表
    self.theInspectModel = [[Model_Hr_Ns_Inspect_New alloc]init];
    // 明细表
    self.theInspectDetailArray = [[NSMutableArray alloc]init];
    
    self.theParamCodeModel = codeModel;
    
    TableQcStandard *standard = [[TableQcStandard alloc]init];
    self.theDataSource = [NSMutableDictionary new];
    
    
    // 主表 赋值
    self.theInspectModel.RESULT_ID = self.InspectModel.CHECK_DATE;
    self.theInspectModel.LEVEL_ID = @"2";
    self.theInspectModel.CODE_ID = codeModel.CODE_ID;
    self.theInspectModel.TYPE_ID = self.theParamCodeModel.TYPE_ID;
    self.theInspectModel.STANDARD_ID = self.theParamCodeModel.STANDARD_ID;
    self.theInspectModel.DEPT_ID = @"需要从人员所属的部门找";
    
    self.theInspectModel.RESUL = self.InspectModel.RESUL?:@""; //    总分
    self.theInspectModel.SCORE = self.InspectModel.SCORE?:@""; //    得分
    
    // 被考核人
    self.theInspectModel.NURSE_ID = self.InspectModel.NURSE_ID?:@"";
    self.theInspectModel.NURSE_NAME = self.InspectModel.NURSE_NAME?:@"";
    
    // 考核人
    self.theInspectModel.CHECK_DATE = self.InspectModel.CHECK_DATE;
    self.theInspectModel.CHECKER_NAME = [UserDefault getUserInfo].USER_NAME;
    self.theInspectModel.CHECKER_ID = [UserDefault getUserInfo].EMP_ID;
    
    // 新增人，编辑人字段
    self.theInspectModel.MODIFY_DATE = self.InspectModel.MODIFY_DATE;
    self.theInspectModel.MODIFY_USER_ID = [UserDefault getUserInfo].USER_ID;
    self.theInspectModel.MODIFY_USER_NAME = [UserDefault getUserInfo].USER_NAME;
    self.theInspectModel.INPUT_DATE = self.InspectModel.INPUT_DATE;
    self.theInspectModel.INPUT_USER_ID = [UserDefault getUserInfo].USER_ID;
    self.theInspectModel.INPUT_USER_NAME = [UserDefault getUserInfo].USER_NAME;
    
    self.theInspectModel.ISSUBMIT = 1;
    self.theInspectModel.CHECK_STATUS = 2;
    self.theInspectModel.UPLOAD_FLAG = 0;
    
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    
    self.theSecondCodeArray = [standard GetQcCodeWithParentId:codeModel.STANDARD_ID parent_id:codeModel.CODE_ID];
    
    CGFloat totalScore = 0;
    InitDbTableQuality *initDb = [[InitDbTableQuality alloc]init];

    self.theInspectDetailArray =  [initDb GetDetailInspectTableWithResult:self.InspectModel.RESULT_ID];

    for (Model_Hr_InspectDetail_New *model in self.theInspectDetailArray) {
        model.RESULT_ID = self.InspectModel.RESULT_ID;
        
    }
    
    for (HQc_codeModel *m in self.theSecondCodeArray) {
        NSArray *arr = [standard GetQcCodeWithParentId:m.STANDARD_ID parent_id:m.CODE_ID];
        [self.theDataSource setObject:arr forKey:m.CODE_ID];
        
//        for (HQc_codeModel *n in arr) {
//            Model_Hr_InspectDetail_New *a = [Model_Hr_InspectDetail_New new];
//            a.RESULT_ID = self.theInspectModel.RESULT_ID;
//            a.CODE_ID = n.CODE_ID;
//            a.SCORE = [n.SCORE floatValue];// 本字段为计算得分，默认满分
//            a.RESION = @"";//扣分原因
//            a.UPLOAD_FLAG = 0;
//            a._flag_eidted_ = 0;
//            totalScore += [n.SCORE floatValue];
//            [self.theInspectDetailArray addObject:a];
//        }
    }
    
    self.theInspectModel.RESUL = [NSString stringWithFormat:@"%.2f",totalScore];
    
    return self;
}


- (void)viewDidLoad {
    
    UIBarButtonItem *savebtn = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(didSaveButttonClicked:)];
    if (self.typeTag == 1) {
        self.navigationItem.rightBarButtonItem = savebtn;
    }
    [self.view addSubview:self.theTableView];
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


-(IBAction)didSaveButttonClicked:(id)sender{
    if( [self.theInspectModel.NURSE_NAME isEqualToString:@""]){
        [HCommon popupErrorMessage:@"请选择被考核人"];
        return;
    }
    
    [[HQualitySave alloc]initWithUpdateFormData:self.InspectModel inspectDetailArray:self.theInspectDetailArray];
    [self.navigationController popViewControllerAnimated:YES];
    NSNotification * notice = [NSNotification notificationWithName:@"UploadSuccess" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice];
    [HCommon popupSuccessMessage:@"保存成功"];

}

- (UITableView *)theTableView
{
    if (!_theTableView) {
        _theTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, NavBarHeight, ScreenWidth , ScreenHeight - NavBarHeight) style: UITableViewStyleGrouped];
        _theTableView.dataSource = self;
        _theTableView.delegate = self;
        _theTableView.tableFooterView = [[UIView alloc]init];
        //[_theTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
        [_theTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [_theTableView setTableHeaderView: [self GetTableHeaderView]];
    }
    return _theTableView;
}


// 头部视图 - 姓名 - 考核人 - 考核时间 等


- (UIView *) GetTableHeaderView
{
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    headView.backgroundColor = RGB(247, 247,247);
    
    
    CGFloat spacing = 10;
    CGFloat left = 10;
    CGFloat right = 10;
    CGFloat titleLableWidth = 100;
    UIColor *fontColor = UIColor.blackColor; //RGB(0x33,0x99,0x66);
    
    UILabel *code_name = [[UILabel alloc]initWithFrame:CGRectMake(left, 0 + spacing , ScreenWidth , 50)];
    code_name.text = [NSString stringWithFormat:@"考核内容：%@", self.theParamCodeModel.CODE_NAME];
    code_name.lineBreakMode = NSLineBreakByWordWrapping;
    code_name.numberOfLines = 0;
    code_name.font = [UIFont systemFontOfSize:17];
    
    
    UILabel *nurse_name = [[UILabel alloc]initWithFrame:CGRectMake(left, code_name.bottom + spacing, titleLableWidth, 35)];
    nurse_name.text = @"姓名:";
    
    // 这里是将一个按钮做一个文本框用 ， 将人名做按钮标题
    UITextField *nurse_name_textfield = [[UITextField alloc]init];
    nurse_name_textfield.frame = CGRectMake(nurse_name.right, code_name.bottom + spacing, ScreenWidth - nurse_name.right - right, 30);
    nurse_name_textfield.borderStyle = UITextBorderStyleRoundedRect;
    nurse_name_textfield.enabled = YES;
    nurse_name_textfield.text = self.InspectModel.NURSE_NAME;
    nurse_name_textfield.placeholder = @"点击选择被考核人";
    nurse_name_textfield.textColor = fontColor;
    nurse_name_textfield.delegate = self;
    
    
    UILabel *check_date = [[UILabel alloc]initWithFrame:CGRectMake(left,nurse_name.bottom + spacing, titleLableWidth, 30)];
    check_date.text = @"考核日期:";
    //check_date.font = [UIFont systemFontOfSize:15];
    
    UITextField *check_date_textfield = [[UITextField alloc]init];
    check_date_textfield.frame = CGRectMake(check_date.right, nurse_name.bottom + spacing, ScreenWidth - check_date.right - right, 30);
    check_date_textfield.borderStyle = UITextBorderStyleRoundedRect;
    check_date_textfield.enabled = NO;
    check_date_textfield.text = self.theInspectModel.CHECK_DATE;
    check_date_textfield.textColor = fontColor;
    
    UILabel *check_name = [[UILabel alloc]initWithFrame:CGRectMake(left, check_date.bottom + spacing, titleLableWidth, 30)];
    check_name.text = @"监考人:";
    //check_name.font = [UIFont systemFontOfSize:15];
    
    UITextField *check_name_textfield = [[UITextField alloc]init];
    check_name_textfield.frame = CGRectMake(check_name.right, check_date.bottom + spacing, ScreenWidth - check_name.right - right, 30);
    check_name_textfield.borderStyle = UITextBorderStyleRoundedRect;
    check_name_textfield.enabled = NO;
    check_name_textfield.text = self.theInspectModel.CHECKER_NAME;
    check_name_textfield.textColor = fontColor;
    
    
    UILabel *total_score = [[UILabel alloc]initWithFrame:CGRectMake(left, check_name.bottom + spacing, titleLableWidth, 30)];
    total_score.text = @"总分:";
    //total_score.font = [UIFont systemFontOfSize:15];
    
    UITextField *total_score_textfield = [[UITextField alloc]init];
    total_score_textfield.frame = CGRectMake(total_score.right, check_name.bottom + spacing, ScreenWidth - total_score.right - right, 30);
    total_score_textfield.borderStyle = UITextBorderStyleRoundedRect;
    total_score_textfield.enabled = NO;
    total_score_textfield.text = self.InspectModel.RESUL;
    total_score_textfield.textColor = fontColor;
    
    UILabel *score = [[UILabel alloc]initWithFrame:CGRectMake(left, total_score.bottom + spacing, titleLableWidth, 30)];
    score.text = @"扣分:";
    //score.font = [UIFont systemFontOfSize:15];
    
    
    UITextField *score_textfield = [[UITextField alloc]init];
    score_textfield.frame = CGRectMake(score.right, total_score.bottom + spacing, ScreenWidth - score.right - right, 30);
    score_textfield.borderStyle = UITextBorderStyleRoundedRect;
    score_textfield.enabled = NO;
    if ([self.InspectModel.SCORE isEqualToString:@"0"]) {
        score_textfield.text = @"0";
    }else {
        score_textfield.text = [NSString stringWithFormat:@"%.2f",[self.InspectModel.RESUL floatValue] - [self.InspectModel.SCORE floatValue]]?:@"0";

    }
    score_textfield.textColor = fontColor;
    
    // 1
    [headView addSubview:code_name];
    // 2
    [headView addSubview:nurse_name];
    // 3
    [headView addSubview:nurse_name_textfield];
    // 4
    [headView addSubview:check_date];
    // 5
    [headView addSubview:check_date_textfield];
    // 6
    [headView addSubview:check_name];
    [headView addSubview:check_name_textfield];
    
    // 7
    [headView addSubview:total_score];
    [headView addSubview:total_score_textfield];
    // 8
    [headView addSubview:score];
    // 9
    [headView addSubview:score_textfield];
    
    [headView setHeight:score_textfield.bottom +spacing ];
    
    return headView;
}


/**
 *      通过 code_id 查找 明细表记录 用于更新 cell 字体颜色等
 */
-(Model_Hr_InspectDetail_New *) getTheInspectDetailWithCodeId:(NSString *)codeid{
    for (Model_Hr_InspectDetail_New *m in self.theInspectDetailArray) {
        //if(m.CODE_ID == codeid){
        if( [m.CODE_ID isEqualToString:codeid]){
            return m;
        }
    }
    return nil;
}
/**
 *      通过 code_id 查找 明细表记录 并使用 CallBack 返回的数据更新集合记录
 */
-(void) setTheInspectDetail : (NSDictionary*) dict{
    
    NSString *codeid = [dict valueForKey:@"CODE_ID"];
    NSString *kfyy = [dict valueForKey:@"KFYY"];
    CGFloat df = [[dict valueForKey:@"DF"] floatValue];
    for (Model_Hr_InspectDetail_New *m in self.theInspectDetailArray) {
        if(m.CODE_ID == codeid){
            m.SCORE = df;
            m.RESION = kfyy;
            m._flag_eidted_ = 1;
            
            [self setTotalDeductionScore:[[dict valueForKey:@"KF"] floatValue]];
            
            break;
        }
    }
    
}

-(void) setTotalDeductionScore:(CGFloat)kf{
    CGFloat total = 0;
    
    UIView *tableHeadview = [self.theTableView tableHeaderView];
    UITextField *zftf = tableHeadview.subviews[10];
    total = [zftf.text floatValue];
    
    total += kf;
    
    zftf.text = [NSString stringWithFormat:@"%0.1f",total];
    
    // 总得分=总分-总扣分
    self.InspectModel.SCORE = F(@"%.1f",[self.InspectModel.RESUL floatValue] - total);
    
}

#pragma mark  委托  UITextFiled
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    
    // 调用找人控件，关闭键盘
    HQCDepartViewController *vc  =[[HQCDepartViewController alloc]initWithType:2 modelArray:nil standard_id:0];
    UINavigationController *nv = [[UINavigationController alloc]initWithRootViewController:vc];
    
    vc.title = @"选择人员";
    vc.hidesBottomBarWhenPushed = YES;
    vc.modalPresentationStyle = UIModalPresentationFormSheet;
    vc.modalTransitionStyle = UIModalPresentationPopover;
    vc.getBlock = ^(NSArray *array)  {
        Model_Pub_Employee *employeeModel = array[0];
        textField.text = employeeModel.EMP_NAME;
        self.theInspectModel.NURSE_ID = employeeModel.EMP_ID;
        self.theInspectModel.NURSE_NAME = employeeModel.EMP_NAME;
        self.theInspectModel.DEPT_ID = employeeModel.DEPT_ID6;
    };
    
    [self.view.window.rootViewController presentViewController:nv animated:true completion:nil];
    
    [textField resignFirstResponder];
}
- (BOOL)textFieldShouldClear:(UITextField *)textField;{
    return  NO;
}


#pragma mark  委托  UITableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.theDataSource.allKeys.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    HQc_codeModel *model = self.theSecondCodeArray[section];
    
    UILabel *sectionHeader = [[UILabel alloc] initWithFrame:CGRectNull];
    sectionHeader.backgroundColor = [UIColor groupTableViewBackgroundColor];
    sectionHeader.font = [UIFont boldSystemFontOfSize:16];
    //sectionHeader.textColor = [UIColor blueColor];
    sectionHeader.text = [NSString stringWithFormat:@"%@. %@",[super ChineseWithInteger: section + 1], model.CODE_NAME];
    
    sectionHeader.lineBreakMode = NSLineBreakByWordWrapping;
    sectionHeader.numberOfLines = 0;
    
    return sectionHeader;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    HQc_codeModel *model = self.theSecondCodeArray[section];
    NSArray *arr = self.theDataSource[model.CODE_ID];
    return arr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"cell";
    UITableViewCell *cell = [self.theTableView dequeueReusableCellWithIdentifier:cellID];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
    }
    
    HQc_codeModel *code = self.theSecondCodeArray[indexPath.section];
    NSArray *arr = self.theDataSource[code.CODE_ID];
    HQc_codeModel *model = arr[indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%ld. %@ (%.1f分)\n",indexPath.row + 1 ,model.CODE_NAME, [model.SCORE floatValue] ];
    //    cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
    //    cell.textLabel.numberOfLines = 1;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.textColor = UIColor.blackColor;
    cell.detailTextLabel.textColor = UIColor.blackColor;
    cell.detailTextLabel.text = @"";
    
    // code id;
    Model_Hr_InspectDetail_New *editdata = [self getTheInspectDetailWithCodeId:model.CODE_ID];
    if(editdata != nil){
        if(editdata.SCORE != [model.SCORE floatValue]){
            NSString *kf = [NSString stringWithFormat:@"▸ 扣%.1f分", [model.SCORE floatValue] - editdata.SCORE];
            cell.detailTextLabel.textColor = UIColor.redColor;
            cell.detailTextLabel.text = kf;
            
            //cell.textLabel.textColor = RGB(0x00, 0x33, 0x00);
            //cell.textLabel.text = [NSString stringWithFormat:@"%ld. %@ (%.1f分) %@",indexPath.row + 1 ,model.CODE_NAME, [model.SCORE floatValue], kf ];
        }
        else{
            
            if( editdata._flag_eidted_ == 1){
                
                NSString *kf = @"▸ 满分";
                cell.detailTextLabel.textColor = UIColor.blueColor;
                cell.detailTextLabel.text = kf;
                
                //cell.textLabel.textColor = RGB(0x00, 0x33, 0x00);
                //cell.textLabel.text = [NSString stringWithFormat:@"%ld. %@ (%.1f分) %@",indexPath.row + 1 ,model.CODE_NAME, [model.SCORE floatValue], kf ];
            }
        }
    }
    
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HQc_codeModel *code = self.theSecondCodeArray[indexPath.section];
    NSArray *arr = self.theDataSource[code.CODE_ID];
    HQc_codeModel *model = arr[indexPath.row];
    
    Model_Hr_InspectDetail_New *editdata = [self getTheInspectDetailWithCodeId:model.CODE_ID];
    
    HNurseAssessFormViewController *vc = [[HNurseAssessFormViewController alloc]initWithCodeModel:model NSIndexPath:indexPath Model_Hr_InspectDetail_New:editdata];
    UINavigationController *nv = [[UINavigationController alloc]initWithRootViewController:vc];
    
    vc.delegate = self;
    vc.title = @"考核情况录入";
    vc.hidesBottomBarWhenPushed = YES;
    vc.modalPresentationStyle = UIModalPresentationFormSheet;
    vc.modalTransitionStyle = UIModalPresentationPopover;
    
    [self.view.window.rootViewController presentViewController:nv animated:true completion:nil];
}

// delegate of HNurseAssessForm

// DF,KF,KFYY,CODE_ID 字典项
-(void)CallBackWithIndexPath:(NSObject*)object NSIndexPath:(NSIndexPath*)indexPath{
    
    NSDictionary *dict = (NSDictionary*)object;
    
    [self setTheInspectDetail:dict];
    
    [self.theTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil]withRowAnimation: UITableViewRowAnimationFade];
}

@end
